<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-overlay">
      <view class="loading-content">
        <uni-icons type="spinner-cycle" size="30" color="#7B6CF7"></uni-icons>
        <text class="loading-text">数据加载中...</text>
      </view>
    </view>

    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-item" :class="{ active: currentView === 'day' }" @click="switchView('day')">
        日统计
      </view>
      <view class="nav-item" :class="{ active: currentView === 'week' }" @click="switchView('week')">
        周统计
      </view>
    </view>

    <!-- 周统计内容 -->
    <view v-if="currentView === 'week'" class="week-view">
      <!-- 睡眠时长卡片 -->
      <view class="card">
        <view class="card-header">
          <text class="title">睡眠时长</text>
          <view class="stats">
            <text class="stat-value">{{ weekData.avgSleepTime }}</text>
            <text class="stat-label">周平均</text>
          </view>
        </view>
        <qiun-data-charts type="column" :opts="opts" :chartData="weekData.sleepTimeData" />
      </view>

      <!-- 睡眠时间分布卡片 -->
      <view class="card">
        <view class="card-header">
          <text class="title">睡眠时间分布</text>
          <view class="stats">
            <text class="stat-value">{{ weekData.avgSleepRange }}</text>
            <text class="stat-label">平均时段</text>
          </view>
        </view>
        <qiun-data-charts type="column" :opts="optSleep" :chartData="weekData.sleepDistributionData" />
      </view>

      <!-- 睡眠质量卡片 -->
      <view class="card">
        <view class="card-header">
          <text class="title">睡眠质量得分</text>
          <view class="stats">
            <text class="stat-value">{{ weekData.avgSleepScore }}分</text>
            <text class="stat-label">周平均</text>
          </view>
        </view>
        <qiun-data-charts type="column" :opts="sleepQuality" :chartData="weekData.sleepQualityData" />
      </view>
    </view>

    <!-- 日统计内容 -->
    <view v-else class="day-view">
      <!-- 睡眠概览卡片 -->
      <view class="card">
        <view class="day-header">
          <text class="date">{{ currentDate }}</text>
        </view>

        <!-- 睡眠质量得分 -->
        <view class="score-container">
          <text class="score-title">睡眠质量得分</text>
          <view class="score-main">
            <text class="score-value">{{ dayData.sleepScore }}</text>
            <text class="score-unit">分</text>
          </view>
        </view>

        <!-- 睡眠类型和时长 -->
        <view class="sleep-period">
          <text class="period-label">{{ dayData.sleepType === 'night' ? '夜间睡眠' : dayData.sleepType === 'nap' ? '午睡' :
            '小憩' }}</text>
          <text class="period-time">{{ dayData.mainSleep }}</text>
          <text class="period-range">{{ dayData.sleepRange }}</text>
        </view>

        <!-- 睡眠阶段条形图 -->
        <qiun-data-charts type="column" :opts="daySleepBarOpts" :chartData="daySleepBarData" />
      </view>

      <!-- 睡眠结构卡片 -->
      <view class="card">
        <view class="card-header">
          <text class="title">睡眠结构</text>
          <view class="stats">
            <text class="stat-value">{{ dayData.totalSleep }}</text>
          </view>
        </view>

        <view class="sleep-structure">
          <!-- 环形图 -->
          <qiun-data-charts type="ring" :opts="daySleepRingOpts" :chartData="daySleepRingData" />

          <!-- 睡眠阶段详情 -->
          <view class="stage-details">
            <view class="stage-item" v-for="item in dayData.sleepStages" :key="item.name">
              <view class="stage-color" :style="{ backgroundColor: item.color }"></view>
              <text class="stage-name">{{ item.name }}</text>
              <text class="stage-percent">{{ item.percent }}% </text>
              <text class="stage-time">({{ item.time }})</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 睡眠建议卡片 -->
      <view class="card advice-card">
        <view class="card-header">
          <text class="title">睡眠解读与建议</text>
        </view>
        <text class="advice-text">{{ dayData.sleepAdvice }}</text>
      </view>

      <!-- 零星小睡卡片 -->
      <view class="card nap-card" v-if="dayData.napTime">
        <view class="card-header">
          <text class="title">零星小睡</text>
        </view>
        <text class="nap-time">{{ dayData.napTime }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { get } from '@/utils/request.js'
import { useHealthData } from '../../../store/modules/useHealthData'
const healthDataStore = useHealthData()

const USER_ID = healthDataStore.getCurUserId // 这里应该从用户状态或路由参数中获取
const currentView = ref('day')
const currentDate = ref(formatDate(new Date()))
const isLoading = ref(false)

// 日统计数据
const dayData = ref({
  sleepScore: 0,
  mainSleep: "",
  sleepRange: "",
  totalSleep: "",
  sleepStages: [],
  sleepAdvice: "",
  napTime: null,
  sleepType: ""
})

// 周统计数据
const weekData = ref({
  sleepTimeData: { categories: [], series: [] },
  sleepDistributionData: { categories: [], series: [] },
  sleepQualityData: { categories: [], series: [] },
  avgSleepTime: "",
  avgSleepRange: "",
  avgSleepScore: 0,
  totalNapTime: ""
})

const opts = ref({
  color: ["#7B6CF7", "#B987F8"],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {
    position: "bottom",
    margin: 10
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 2,
    data: [
      {
        min: 0,
        axisLineColor: "#E4E7ED",
        splitLineColor: "#F7F8FA"
      }
    ]
  },
  extra: {
    column: {
      type: "stack",
      width: 18,
      activeBgColor: "#000000",
      activeBgOpacity: 0.08,
      labelPosition: "center"
    }
  }
})

const optSleep = ref({
  color: ['#7B6CF7', '#3B82F6'],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {
    position: "bottom",
    margin: 10
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 2,
    data: [{
      min: 0,
      max: 24,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: v => {
        const h = Math.floor(v)
        const m = Math.floor((v - h) * 60)
        return `${h}:${m < 10 ? '0' + m : m}`
      }
    }]
  },
  extra: {
    column: {
      width: 12,
      categoryGap: '30%'
    }
  }
})

const sleepQuality = ref({
  color: ['#7B6CF7'],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 2,
    data: [{
      min: 0,
      max: 100,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: val => `${val}分`
    }]
  },
  extra: {
    column: {
      width: 20,
      categoryGap: '60%',
      linearType: "custom",
      linearOpacity: 1,
      linearColor: ["#7B6CF7", "#B987F8"]
    }
  }
})

const daySleepBarOpts = ref({
  color: ["#3B82F6", "#60A5FA", "#93C5FD"],
  padding: [15, 30, 10, 15],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED",
    labelCount: 2
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    splitNumber: 3,
    data: [{
      min: 0,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA"
    }]
  },
  extra: {
    column: {
      type: "group",
      width: 20,
      categoryGap: 2,
      activeBgColor: "#000000",
      activeBgOpacity: 0.08
    }
  }
})

const daySleepRingOpts = ref({
  color: ["#3B82F6", "#60A5FA", "#93C5FD"],
  padding: [5, 5, 5, 5],
  enableScroll: false,
  legend: {
    show: false
  },
  title: {
    name: '',
    fontSize: 18,
    color: "#7cb5ec",
  },
  subtitle: {
    name: '',
    fontSize: 18,
    color: "#7cb5ec"
  },
  extra: {
    pie: {
      ringWidth: 30,
      label: {
        show: false
      }
    },
    label: {
      show: false
    }
  }
})

// 计算属性：日统计图表数据
const daySleepBarData = computed(() => {
  if (!dayData.value || !dayData.value.sleepStages) {
    return {
      categories: ["睡眠阶段"],
      series: []
    }
  }

  return {
    categories: ["睡眠阶段"],
    series: dayData.value.sleepStages.map(stage => ({
      name: stage.name,
      data: [parseFloat(stage.time)]
    }))
  }
})

function convertTimeToHours(timeStr) {
  const matches = timeStr.match(/(\d+)小时(\d+)分钟/);
  if (!matches) return 0;
  
  const hours = parseInt(matches[1]);
  const minutes = parseInt(matches[2]);
  return parseFloat((hours + minutes / 60).toFixed(1));
}

const daySleepRingData = computed(() => {
  if (!dayData.value || !dayData.value.sleepStages) {
    return { series: [] }
  }

  return {
    series: dayData.value.sleepStages.map(stage => ({
      name: stage.name,
      data: convertTimeToHours(stage.time), // 转换时长为小时数
    }))
  }
})

// 加载数据函数
async function loadData() {
  try {
    isLoading.value = true
    console.log('user:',USER_ID,healthDataStore.getCurUserId)

    const res = await get(`/sleep/${USER_ID}/statistics?period=${currentView.value}`, 'api/v1')

    if (res.code === 200 && res.data) {
      if (currentView.value === 'day') {
        // 验证日统计数据
        if (validateDayData(res.data)) {
          dayData.value = res.data
        } else {
          throw new Error('日统计数据格式不正确')
        }
      } else {
        // 验证周统计数据
        if (validateWeekData(res.data)) {
          weekData.value = res.data
        } else {
          throw new Error('周统计数据格式不正确')
        }
      }
    } else {
      throw new Error(res.message || '数据加载失败')
    }
    daySleepRingOpts.value.title.name = dayData.value.totalSleep || '0'
    // daySleepRingOpts.value.subtitle.name = '/h' || ''


  } catch (error) {
    console.error('加载数据失败:', error)
    uni.showToast({
      title: error.message || '数据加载失败',
      icon: 'none',
      duration: 2000
    })
  } finally {
    // 添加短暂延迟确保数据完全加载
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
}

// 验证日统计数据
function validateDayData(data) {
  return data &&
    typeof data.sleepScore === 'number' &&
    typeof data.mainSleep === 'string' &&
    typeof data.sleepRange === 'string' &&
    typeof data.totalSleep === 'string' &&
    typeof data.sleepType === 'string' &&
    Array.isArray(data.sleepStages) &&
    data.sleepStages.every(stage =>
      typeof stage.name === 'string' &&
      typeof stage.percent === 'number' &&
      typeof stage.time === 'string' &&
      typeof stage.color === 'string'
    )
}

// 验证周统计数据
function validateWeekData(data) {
  return data &&
    data.sleepTimeData &&
    data.sleepDistributionData &&
    data.sleepQualityData &&
    Array.isArray(data.sleepTimeData.categories) &&
    Array.isArray(data.sleepTimeData.series) &&
    Array.isArray(data.sleepDistributionData.categories) &&
    Array.isArray(data.sleepDistributionData.series) &&
    Array.isArray(data.sleepQualityData.categories) &&
    Array.isArray(data.sleepQualityData.series) &&
    typeof data.avgSleepTime === 'string' &&
    typeof data.avgSleepRange === 'string' &&
    typeof data.avgSleepScore === 'number' &&
    typeof data.totalNapTime === 'string'
}

// 切换视图
function switchView(view) {
  currentView.value = view
  loadData()
}

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month}月${day}日`
}

// 监听视图变化
watch(currentView, () => {
  loadData()
})

// 页面加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #F7F8FA;
  min-height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .nav-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    transition: all 0.3s;

    &.active {
      color: #7B6CF7;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 4rpx;
        background-color: #7B6CF7;
        border-radius: 2rpx;
      }
    }
  }
}

/* 卡片通用样式 */
.card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .stats {
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .stat-value {
      font-size: 28rpx;
      font-weight: 500;
      color: #7B6CF7;
    }

    .stat-label {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }

  .support {
    font-size: 24rpx;
    color: #999;
  }
}

/* 日统计头部 */
.day-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;

  .date {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }

  .source {
    font-size: 24rpx;
    color: #999;
  }
}

/* 睡眠质量得分 */
.score-container {
  text-align: center;
  margin: 20rpx 0 30rpx;

  .score-title {
    font-size: 28rpx;
    color: #666;
  }

  .score-main {
    display: flex;
    justify-content: center;
    align-items: baseline;
    margin: 10rpx 0;

    .score-value {
      font-size: 72rpx;
      font-weight: bold;
      color: #333;
    }

    .score-unit {
      font-size: 32rpx;
      color: #666;
      margin-left: 8rpx;
    }
  }

  .score-comment {
    font-size: 26rpx;
    color: #FF6B6B;
  }
}

/* 睡眠动物卡片 */
.animal-card {
  background: #F0F7FF;
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  margin: 20rpx 0;

  .animal-icon {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }

  .animal-text {
    font-size: 28rpx;
    color: #3B82F6;
    font-weight: 500;
  }
}

/* 睡眠时段 */
.sleep-period {
  display: flex;
  align-items: center;
  margin: 20rpx 0;
  padding: 16rpx;
  background-color: #F7F8FA;
  border-radius: 12rpx;

  .period-label {
    font-size: 28rpx;
    color: #666;
    margin-right: 20rpx;
    padding: 4rpx 12rpx;
    background-color: #E8EAF6;
    border-radius: 8rpx;
  }

  .period-time {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    margin-right: 20rpx;
  }

  .period-range {
    font-size: 26rpx;
    color: #999;
  }
}

/* 睡眠结构 */
.sleep-structure {
  display: flex;
  align-items: center;
  margin-top: 20rpx;

  .stage-details {
    flex: 1;
    margin-left: 40rpx;
  }

  .stage-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .stage-color {
      width: 24rpx;
      height: 24rpx;
      border-radius: 6rpx;
      margin-right: 16rpx;
    }

    .stage-name {
      font-size: 26rpx;
      color: #666;
      width: 120rpx;
    }

    .stage-percent {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
      width: 80rpx;
      text-align: right;
      margin-right: 10rpx;
    }

    .stage-time {
      font-size: 24rpx;
      color: #999;
    }
  }
}

/* 健康指标 */
.health-metrics {
  .metric-item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #F0F0F0;

    &:last-child {
      border-bottom: none;
    }

    .metric-label {
      font-size: 28rpx;
      color: #666;
    }

    .metric-value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

/* 睡眠建议 */
.advice-card {
  .advice-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .view-more {
    display: block;
    text-align: right;
    font-size: 26rpx;
    color: #3B82F6;
    margin-top: 20rpx;
  }
}

/* 零星小睡 */
.nap-card {
  .nap-time {
    font-size: 28rpx;
    color: #333;
    padding: 16rpx;
    background-color: #F7F8FA;
    border-radius: 12rpx;
  }
}

/* 图表容器 */
qiun-data-charts {
  display: block;
  width: 100%;
  height: 360rpx;
}

/* 添加加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.uni-icons {
  animation: rotate 1s linear infinite;
}
</style>